package com.ctu.autodial.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;

import com.ctu.app.utils.ConfigureLog4J;
//import com.ctu.app.utils.LogUtil;
import com.ctu.autodial.MainActivity;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;

/**
 * Created by kaiz on 14-3-6.
 */
public class SimulateEvent {
	private static final String TAG = "SimulateEvent";
	private static final String EXCEPTION_FILE_NAME = "AutoDialRunException";
	private static Logger runLogger;
	static char num;

	public SimulateEvent() {
		// TODO Auto-generated constructor stub
		runLogger = ConfigureLog4J.configure();

	}

	/*
	 * kaiz: 0~9一样，*：11，#：12
	 */
	public static void InputNumber(int num) {
		Log.d(TAG, "键盘输入-->" + num);
		int x = 0;
		int y = 0;
		switch (num) {
		case 1:
			x = 40;
			y = 105;
			break;
		case 2:
			x = 140;
			y = 105;
			break;
		case 3:
			x = 240;
			y = 105;
			break;
		case 4:
			x = 40;
			y = 170;
			break;
		case 5:
			x = 140;
			y = 170;
			break;
		case 6:
			x = 240;
			y = 170;
			break;
		case 7:
			x = 40;
			y = 230;
			break;
		case 8:
			x = 140;
			y = 230;
			break;
		case 9:
			x = 240;
			y = 230;
			break;
		case 0:
			x = 140;
			y = 290;
			break;
		case 11:
			x = 40;
			y = 290;
			break;
		case 12:
			x = 240;
			y = 290;
			break;
		}
		click(x, y);
	}

	/**
	 * 单击
	 * 
	 * @param x
	 * @param y
	 */
	public static boolean click(int x, int y) {

		String[] events = getClickEvents(x, y);
		return sendEvents(events);
	}

	/**
	 * 发送事件
	 * 
	 * @param events
	 */
	static boolean sendEvents(String[] events) {
		try {
			Process suProcess = Runtime.getRuntime().exec("su");
			DataOutputStream os = new DataOutputStream(
					suProcess.getOutputStream());
			for (String event : events) {
				os.writeBytes(event + "\n");
				os.flush();
			}

			return true;
		} catch (Throwable e) {
			e.printStackTrace();
			runLogger.error("sendEvents", e);
			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
		}
		return false;
	}

	/**
	 * 获取点击事件
	 * 
	 * @param cmd
	 * @return
	 * @throws Exception
	 */
	private static String getShellResult(String cmd) {
		runLogger.info("getShellResult@@@@@@@@@@@@@@@@@@@@");
		// LogUtil.saveLog2File("getShellResult@@@@@@@@@@@@@@@@@@@@");
		final StringBuffer result = new StringBuffer();
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
			runLogger.error("获取avm root权限...", e);
			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
		}
		InputStream istream = process.getInputStream();
		BufferedReader dataIstream = null;

		try {
			dataIstream = new BufferedReader(new InputStreamReader(istream,
					"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			runLogger.error("getShellResult", e);
			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
		}

		String line = null;

		try {
			while ((line = dataIstream.readLine()) != null) {
				result.append(line + "\n");
			}
			dataIstream.close();
		} catch (IOException e) {
			e.printStackTrace();
			runLogger.error("read inputStream ...", e);
			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
		}
		if (result != null) {
			return result.toString();
		} else {
			return null;
		}

	}

	public static void getEventId() {
		runLogger.info("getEventId@@@@@@@@@@@@@@@@@@@@");
		// LogUtil.saveLog2File("getEventId@@@@@@@@@@@@@@@@@@@@");
		String shellData = "";
		try {
			shellData = SimulateEvent.getShellResult("su -c  getevent -s 0");
		} catch (Exception e) {
			e.printStackTrace();
			runLogger.error("getEventId", e);
			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);

		}

		if (!(TextUtils.isEmpty(shellData))) {
			num = SimulateEvent.parseEventData(shellData);
		}
	}

	/**
	 * 解析当前触摸屏的/dev/input/eventx
	 * 
	 * @param eventData
	 * @return
	 */
	private static char parseEventData(String eventData) {
		runLogger.info("parseEventData@@@@@@@@@@@@@@@@@@@@");
		// LogUtil.saveLog2File("parseEventData@@@@@@@@@@@@@@@@@@@@");

		if (eventData.contains("ms-msg21xx")) {// 待扩展//cypress-ts//ms-msg21xx
			String data = eventData.substring(0,
					eventData.indexOf("ms-msg21xx"));
			char eventChar = data.substring(data.lastIndexOf("/event"),
					data.length()).charAt(6);
			runLogger.info("获取到触摸屏设备号：" + eventChar);
			// LogUtil.saveLog2File("获取到触摸屏设备号：" + eventChar);
			return eventChar;

		} else {
			return 0;
		}

	}

	static String[] getClickEvents(int x, int y) {

		Log.d(TAG, "getClickEvents: ");
		String[] events = new String[18];
		events[0] = "sendevent /dev/input/event" + num + " 0 2 0";

		Log.d(TAG, "events[0]: " + events[0]);
		events[1] = "sendevent /dev/input/event" + num + " 0 0 0";
		events[2] = "sendevent /dev/input/event" + num + " 3 48 1";
		events[3] = "sendevent /dev/input/event" + num + " 3 53 " + x;
		events[4] = "sendevent /dev/input/event" + num + " 3 54 " + y;

		events[5] = "sendevent /dev/input/event" + num + " 0 2 0";
		events[6] = "sendevent /dev/input/event" + num + " 0 0 0";
		events[7] = "sendevent /dev/input/event" + num + " 3 48 1";
		events[8] = "sendevent /dev/input/event" + num + " 3 53 " + x;
		events[9] = "sendevent /dev/input/event" + num + " 3 54 " + y;

		events[10] = "sendevent /dev/input/event" + num + " 0 2 0";
		events[11] = "sendevent /dev/input/event" + num + " 0 0 0";

		events[12] = "sendevent /dev/input/event" + num + " 0 2 0";
		events[13] = "sendevent /dev/input/event" + num + " 0 0 0";

		events[14] = "sendevent /dev/input/event" + num + " 0 2 0";
		events[15] = "sendevent /dev/input/event" + num + " 0 0 0";

		events[16] = "sendevent /dev/input/event" + num + " 0 2 0";
		events[17] = "sendevent /dev/input/event" + num + " 0 0 0";

		return events;
	}

}
